<template>
  <div>
    <Card>
      <tables ref="tables"
              searchable
              search-place="top"
              v-model="tableData"
              :columns="columns"
              @on-row-edit="handleRowEdit"
              @on-row-remove="handleRowRemove"
              @on-selection-change="handleSelect"
              @searchEvent="handleSearch">
        <template v-slot:table-header>
          <Button class="search-btn"
                  type="primary"
                  @click="handleAddUser">
            <Icon type="md-person-add" />&nbsp;&nbsp;新增用户
          </Button>
        </template>
      </tables>
      <Row type="flex"
           justify="space-between"
           align="middle">
        <Col class="ctrls">
        <Button @click="handleDeleteBatch()">批量删除</Button>
        <Button @click="handleSetBatch()">批量设置</Button>
        <Button style="margin: 10px 0;"
                type="primary"
                @click="exportExcel">
          <Icon type="md-download"></Icon>导出表格
        </Button>
        </Col>
        <Col>
        <Page :total="total"
              :current="page"
              :page-size="limit"
              :page-size-opts="pageArr"
              show-elevator
              show-sizer
              show-total
              @on-change="onPageChange"
              @on-page-size-change="onPageSizeChange" />
        </Col>
      </Row>
    </Card>
    <EditModel :isShow="showEdit"
               :item="currentItem"
               :roles="roles"
               @editEvent="handleItemEdit"
               @changeEvent="handleChangeEvent"></EditModel>
    <AddModel ref="addModel"
              :roles="roles"
              @editEvent="handleItemAdd"></AddModel>
    <BatchSet :isShow="showSet"
              :roles="roles"
              @editEvent="handleItemSet"
              @changeEvent="handleSetChangeEvent"></BatchSet>
  </div>
</template>

<script>
import { userDispatch, roleDispatch } from '@/service/api/admin'
import Tables from '_c/tables'
import EditModel from './edit'
import AddModel from './add'
import BatchSet from './batchSet'
import getColumns from './columns'
export default {
  name: 'user_management', // => 等价于notCache
  components: {
    Tables,
    EditModel,
    AddModel,
    BatchSet
  },
  data () {
    return {
      page: 1,
      limit: 10,
      total: 0,
      option: {},
      roles: [],
      showEdit: false,
      showAdd: false,
      showSet: false,
      currentIndex: 0,
      currentItem: {},
      columns: getColumns(this),
      pageArr: [10, 20, 30, 50, 100],
      tableData: [],
      selection: []
    }
  },
  computed: {
    roleNames () {
      const tmp = {}
      this.roles.forEach((item) => {
        tmp[item.role] = item.name
      })
      return tmp
    }
  },
  mounted () {
    this.init()
    this._getRoleNames()
  },
  methods: {
    handleDeleteBatch () {
      // 批量进行删除
      if (this.selection.length === 0) {
        this.$Message.info('请选择需要删除的数据！')
        return
      }
      const msg = this.selection.map((o) => o.username).join(',')
      this.$Modal.confirm({
        title: '确定删除用户吗？',
        content: `删除${msg}的用户`,
        onOk: () => {
          const arr = this.selection.map((o) => o._id)
          userDispatch.use('delete', { ids: arr }).then((res) => {
            // this.tableData.splice(index, 1)
            this.tableData.filter((item) => !arr.includes(item._id))
            this.$Message.success('删除成功！')
            //  this.init()
          })
        },
        onCancel: () => {
          this.$Message.info('取消操作！')
        }
      })
    },
    handleSetBatch () {
      // 批量进行删除
      if (this.selection.length === 0) {
        this.$Message.info('请选择需要设置的数据！')
        return
      }
      // 批量进行设置 -> vip, 禁言, 角色
      this.showSet = true
    },
    handleSelect (selection) {
      this.selection = selection
    },
    handleAddUser () {
      // this.showAdd = true
      this.$refs.addModel.show()
    },
    handleChangeEvent (value) {
      this.showEdit = value
    },
    handleAddChangeEvent (value) {
      this.showAdd = value
    },
    handleSetChangeEvent (value) {
      this.showSet = value
    },
    // 添加模态框
    handleItemAdd (item) {
      userDispatch.use('add', item).then((res) => {
        if (res.code === 200) {
          // this.tableData[this.currentIndex] = item
          this.tableData.splice(0, 0, res.data)
        }
      })
    },
    // 编辑模态框
    handleItemEdit (item) {
      userDispatch.use('update', item).then((res) => {
        if (res.code === 200) {
          // this.tableData[this.currentIndex] = item
          this.tableData.splice(this.currentIndex, 1, item)
        } else {
          this.$Message.error(res.msg)
        }
      })
      this.showEdit = false
    },
    // 批量设置模态框
    handleItemSet (settings) {
      const msg = this.selection.map((o) => o.username).join(',')
      this.$Modal.confirm({
        title: '确定修改用户吗？',
        content: `修改${msg}的用户`,
        onOk: () => {
          const arr = this.selection.map((o) => o._id)
          userDispatch.use('batch', { ids: arr, settings }).then((res) => {
            // this.tableData.splice(index, 1)
            this.tableData.map((item) => {
              if (arr.includes(item._id)) {
                for (var keys of Object.keys(settings)) {
                  item[keys] = settings[keys]
                }
              }
            })
            this.$Message.success('批量设置成功！')
            //  this.init()
          })
        },
        onCancel: () => {
          this.$Message.info('取消操作！')
        }
      })
    },
    handleRowEdit (row, index) {
      this.showEdit = true
      this.currentIndex = index
      this.currentItem = { ...row }
    },
    handleRowRemove (row, index) {
      this.$Modal.confirm({
        title: '确定删除用户吗？',
        content: `删除${row.name}的用户`,
        onOk: () => {
          userDispatch.use('delete', { ids: [row._id] }).then((res) => {
            this.tableData.splice(index, 1)
            this.$Message.success('删除成功！')
          })
        },
        onCancel: () => {
          this.$Message.info('取消操作！')
        }
      })
    },
    handleSearch (value) {
      // 判断是否有新的查询内容的传递，把分页数据归0
      if (
        (typeof this.option.search !== 'undefined' &&
          value.search !== this.option.search) ||
        this.option === {}
      ) {
        this.page = 1 // 从1开始
      }
      this.option = value
      this.init()
    },
    onPageChange (page) {
      this.page = page
      this.init()
    },
    onPageSizeChange (size) {
      this.limit = size
      this.init()
    },
    exportExcel () {
      this.$refs.tables.exportCsv({
        filename: `table-${new Date().valueOf()}.csv`
      })
    },
    init () {
      userDispatch
        .use('get', {
          page: this.page - 1,
          limit: this.limit,
          option: this.option
        })
        .then((res) => {
          this.tableData = res.list
          this.total = res.total
        })
    },
    _getRoleNames () {
      roleDispatch.use('roles').then((res) => {
        this.roles = res.list
      })
    }
  }
}
</script>

<style lang="less" scoped>
.ctrls {
  button {
    margin-right: 10px;
  }
}
</style>
